import { useEffect, useState } from 'react'
import { Card, Form, Input, Select, Button, Typography, message } from 'antd'

const { Title, Paragraph } = Typography
const { Option } = Select

const ConfigPanel = () => {
  const [form] = Form.useForm()
  const [configValues, setConfigValues] = useState(null)

  // 页面加载时从 localStorage 读取缓存配置并回显
  useEffect(() => {
    const cached = localStorage.getItem('frp-global-config')
    if (cached) {
      try {
        const config = JSON.parse(cached)
        form.setFieldsValue(config)
        setConfigValues(config)
      } catch {
        // 解析失败不做操作
      }
    }
  }, [form])

  /**保存配置 */
  const handleSubmit = async values => {
    const frpcExists = await checkFrpcExists(values)
    if (!frpcExists) {
      return
    }
    console.log('FRP 配置:', values)
    localStorage.setItem('frp-global-config', JSON.stringify(values, null, 2))
    setConfigValues(values)
    generateAndSaveIni(values)
    message.success('保存成功')
  }

  /**写入ini文件 */
  const generateAndSaveIni = async configValues => {
    if (!configValues) {
      message.warning('请先填写并保存配置')
      return
    }

    try {
      const res = await fetch('http://localhost:3001/generate-ini', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(configValues),
      })

      const data = await res.json()
      if (res.ok) {
        console.log(data.message)
      } else {
        message.error(data || '生成失败')
      }
    } catch (err) {
      message.error('请求失败')
    }
  }

  /**检查frpc.exe是否存在 */
  const checkFrpcExists = async (configValues) => {
    if (!configValues?.frp_path) {
      return message.warning('请先填写并保存配置')
    }

    try {
      const res = await fetch('http://localhost:3001/check-frpc', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ frp_path: configValues.frp_path }),
      })
      const data = await res.json()
      if (res.ok) {
        if (data.exists) {
          console.log('frpc.exe 存在')
          return true
        } else {
          message.error('请检查文件路径, 未找到 frpc.exe')
          return false
        }
      }
    } catch (err) {
      message.error('请求失败')
      return false
    }
  }

  return (
    <div style={{ maxWidth: 700, margin: '0 auto' }}>
      <Title level={4}>FRP 全局配置</Title>

      <Card title='基本配置'>
        <Form
          form={form}
          layout='vertical'
          onFinish={handleSubmit}
          initialValues={{
            server_addr: 'example.com',
            server_port: 7000,
            token: '',
            log_level: 'info',
            frp_path: 'C:/frp',
          }}>
          <Form.Item
            name='server_addr'
            label='服务端地址'
            rules={[{ required: true, message: '请输入服务端地址' }]}>
            <Input placeholder='例如：frp.example.com' />
          </Form.Item>

          <Form.Item
            name='server_port'
            label='服务端端口'
            rules={[{ required: true, message: '请输入服务端端口' }]}>
            <Input type='number' placeholder='例如：7000' />
          </Form.Item>

          <Form.Item name='token' label='身份认证 Token'>
            <Input.Password placeholder='可选，用于身份认证' />
          </Form.Item>

          <Form.Item name='log_level' label='日志级别'>
            <Select>
              <Option value='trace'>trace</Option>
              <Option value='debug'>debug</Option>
              <Option value='info'>info</Option>
              <Option value='warn'>warn</Option>
              <Option value='error'>error</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name='frp_path'
            label='FRP 目录路径'
            rules={[
              { required: true, message: '请输入 FRP 解压后的目录路径' },
            ]}>
            <Input placeholder='例如：D:/frp' />
          </Form.Item>

          <Form.Item>
            <Button type='primary' htmlType='submit'>
              保存配置
            </Button>
          </Form.Item>
        </Form>

        {/* <Button
          type='dashed'
          onClick={generateAndSaveIni}
          style={{ marginRight: 8 }}>
          生成 frpc.toml 文件
        </Button> */}
        {/* <Button onClick={checkFrpcExists} style={{ marginRight: 8 }}>
          检查 frpc.exe 是否存在
        </Button> */}
      </Card>

      <Card title='FRP 文件夹结构示例' style={{ marginTop: 24 }}>
        <Paragraph>解压后的目录应包含以下文件结构：</Paragraph>
        <pre>
          frp/ ├── frpc.exe ├── frpc.ini ├── frps.exe (可选) ├── frps.ini (可选)
          ├── README.md
        </pre>
        <Paragraph type='secondary'>
          后续配置与启动命令将基于该路径自动引用相关文件。
        </Paragraph>
      </Card>
    </div>
  )
}

export default ConfigPanel
